package com.maxd.service.token;

import com.maxd.error.ExceptionEnum;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.AdminInfo;
import com.maxd.model.Token;
import com.maxd.model.UserInfo;
import com.maxd.respository.admin.AdminJpaRepository;
import com.maxd.respository.admin.AdminRepository;
import com.maxd.respository.token.TokenJpaRepository;
import com.maxd.respository.token.TokenRepository;
import com.maxd.respository.userinfo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 全局token的实现类
 */
@Service
public class TokenServiceImpl implements ITokenService {
    @Autowired
    private TokenJpaRepository tokenJpaRepository;
    @Autowired
    private TokenRepository tokenRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private AdminJpaRepository adminJpaRepository;

    @Override
    public void saveBody(Token coupon) {
        tokenJpaRepository.save(coupon);

    }

    @Override
    public void delete(long id) {
        tokenJpaRepository.deleteById(id);
    }

    @Override
    public Token getUserByUuid(String uuid) {
        Token byId = tokenRepository.findOne(uuid);
        return byId;
    }

    @Override
    public UserInfo getUserById(Long userId) {
       return userRepository.getUserById(userId);
    }

    @Override
    public AdminInfo getAdminId(Long userId) {
        return adminJpaRepository.findById(userId).orElse(null);
    }

    @Override
    public Result removeToken(String uuid) {
        Token byId = tokenRepository.findOne(uuid);
        if (byId != null) {
            tokenJpaRepository.deleteById(byId.getId());
            return ResultUtil.success();
        } else {
            return ResultUtil.error(ExceptionEnum.WRONT_TOKEN);
        }
    }
}
